from datetime import timedelta
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from pydantic import BaseModel, EmailStr, Field, ConfigDict

from app.models import get_db
from app.services.auth_service import AuthService
from app.api.users import UserOut  # 复用用户输出模型
from app.utils.response import Response
from app.utils.config_loader import config

router = APIRouter(prefix="/auth", tags=["认证管理"])

# 请求模型
class UserRegister(BaseModel):
    """用户注册请求模型"""
    username: str = Field(..., description="用户名", example="johndoe")
    email: EmailStr = Field(..., description="邮箱", example="john@example.com")
    password: str = Field(..., min_length=6, description="密码", example="secret123")

class UserLogin(BaseModel):
    """用户登录请求模型"""
    username: str = Field(..., description="用户名", example="johndoe")
    password: str = Field(..., description="密码", example="secret123")
    remember_me: Optional[bool] = Field(False, description="记住我")

# 响应模型
class TokenResponse(BaseModel):
    """令牌响应模型"""
    access_token: str = Field(..., description="访问令牌")
    token_type: str = Field("bearer", description="令牌类型")
    user: UserOut = Field(..., description="用户信息")
    
    model_config = ConfigDict(from_attributes=True)

# API接口
@router.post("/register", response_model=dict)
def register(user_data: UserRegister, db: Session = Depends(get_db)):
    """用户注册"""
    user = AuthService.register(
        db,
        username=user_data.username,
        email=user_data.email,
        password=user_data.password
    )
    return Response.success(UserOut.model_validate(user))

@router.post("/login", response_model=dict)
def login(login_data: UserLogin, db: Session = Depends(get_db)):
    """用户登录"""
    # 根据记住我选项设置不同的令牌过期时间
    expires_delta = None
    if login_data.remember_me:
        # 如果记住我，令牌的有效期更长
        expires_delta = timedelta(minutes=config.security.remember_me_expire_minutes)
    
    # 调用登录服务
    result = AuthService.login(
        db,
        username=login_data.username,
        password=login_data.password,
        expires_delta=expires_delta
    )
    
    # 构造响应数据
    token_data = TokenResponse(
        access_token=result["access_token"],
        token_type=result["token_type"],
        user=UserOut.model_validate(result["user"])
    )
    
    return Response.success(token_data.model_dump())

@router.post("/logout", response_model=dict)
def logout(user_id: int):
    """用户登出"""
    AuthService.logout(user_id)
    return Response.success({"message": "登出成功"})
